﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AutoStar.Views
{
    /// <summary>
    /// WindowLogin.xaml 的交互逻辑
    /// </summary>
    public partial class WindowLogin : Window
    {
        public WindowLogin()
        {
            InitializeComponent();
            LoadSettings();
            DataContext = Global.WindowLoginVM;
            this.Closed += WindowLogin_Closed;
            this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            Loaded += WindowLogin_Loaded; // 注册Loaded事件
        }
        private void WindowLogin_Loaded(object sender, RoutedEventArgs e)
        {
            // 现在窗口已经加载，可以安全地调用Close方法
            AutoLoginIfCredentialsAreSaved();
        }
        private void AutoLoginIfCredentialsAreSaved()
        {
            if (!string.IsNullOrEmpty(Global.WindowLoginVM.UserName) && !string.IsNullOrEmpty(passwordBox.Password) && !string.IsNullOrEmpty(Code.Password))
            {
                int result = Login();
                if (result == -1)
                {
                    MessageBox.Show("保存的用户名或密码不正确！");
                    return;
                }
                int resultStatus = VerifyRegistrationCode();
                if (resultStatus == -1)
                {
                    // 注册码验证失败
                    return;
                }
                IsUserLoggedIn = true;
                this.Close();
            }
        }
        private void LoadSettings()
        {
            try
            {
                if (Global.WindowLoginVM.RememberPassword && ConfigurationManager.AppSettings.AllKeys.Contains("UserName"))
                {
                    Global.WindowLoginVM.UserName = config.AppSettings.Settings["UserName"].Value;
                    passwordBox.Password = config.AppSettings.Settings["Password"].Value;
                }
                if (ConfigurationManager.AppSettings.AllKeys.Contains("UserName") &&
                    ConfigurationManager.AppSettings.AllKeys.Contains("Password"))
                {
                    Global.WindowLoginVM.UserName = config.AppSettings.Settings["UserName"].Value;
                    passwordBox.Password = config.AppSettings.Settings["Password"].Value;
                    if (ConfigurationManager.AppSettings.AllKeys.Contains("RegistrationCode"))
                    {
                        string decryptedCode = Global.encryption.Decrypt(config.AppSettings.Settings["RegistrationCode"].Value);
                        string expirationDateStr = decryptedCode.Substring(decryptedCode.Length - 8);
                        string[] strings = decryptedCode.Split('/');
                        Code.Password = strings[3];
                    }
                    Global.WindowLoginVM.RememberPassword = true;
                }
                if(string.IsNullOrEmpty(Global.WindowLoginVM.UserName) 
                    && string.IsNullOrEmpty(passwordBox.Password) 
                    && string.IsNullOrEmpty(Code.Password))
                {
                    Global.WindowLoginVM.UserName = "admin";
                    passwordBox.Password = "0351";
                    Code.Password = "20240425";
                }

                Global.printer.serialPortController.serialPort.PortName = Global.serialVM.SerialPorts[0];
                Global.printer.serialPortController.serialPort.BaudRate = int.Parse(Global.serialVM.BaudRates[5]);
                Global.printer.serialPortController.serialPort.Parity = (Parity)Global.serialVM.ParityBitInt;
                //Global.printer.serialPortController.serialPort.Parity = (Parity)int.Parse(SelectedParityBits);
                Global.printer.serialPortController.serialPort.DataBits = int.Parse(Global.serialVM.DataBits[3]);
                Global.printer.serialPortController.serialPort.StopBits = (StopBits)int.Parse(Global.serialVM.StopBits[0]);
                try
                {
                    Global.MainVM.SwitchSerial();
                    Global.serialVM.SerialButtonText = Global.printer.serialPortController.serialPort.IsOpen ? "关闭串口" : "打开串口";
                    //Global.printer.XYToZero();
                }
                catch (Exception ex)
                {
                    Global.LogHelper.WriteLog(ex.Message);
                    MessageBox.Show("串口自动连接失败，请手动连接！");
                }
            }
            catch
            {
            }
        }
        private void WindowLogin_Closed(object sender, EventArgs e)
        {
            if (!IsUserLoggedIn)
                Application.Current.Shutdown();  // 退出应用程序
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int result = Login();
            if (result == -1)
            {
                MessageBox.Show("用户名或密码不正确！");
                IsUserLoggedIn = false;
                return;
            }
            int resultStatus = VerifyRegistrationCode();
            if (resultStatus == -1)
                return;
            if (Global.WindowLoginVM.RememberPassword)
            {
                if (ConfigurationManager.AppSettings.AllKeys.Contains("UserName"))
                    config.AppSettings.Settings["UserName"].Value = Global.WindowLoginVM.UserName;
                else
                    config.AppSettings.Settings.Add("UserName", Global.WindowLoginVM.UserName);
                if (ConfigurationManager.AppSettings.AllKeys.Contains("Password"))
                    config.AppSettings.Settings["Password"].Value = Global.WindowLoginVM.UserPassword;
                else
                    config.AppSettings.Settings.Add("Password", Global.WindowLoginVM.UserPassword);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appsettings");
            }
            IsUserLoggedIn = true;

            //MainWindow mainWindow = new MainWindow();
            //mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen; 
            //mainWindow.Show();
            this.Close();
        }
        private static bool IsUserLoggedIn = false;
        public static Configuration config = Global.config;
        public static AppSettingsSection settings = config.AppSettings;
        private int VerifyRegistrationCode()
        {
            Global.WindowLoginVM.Code = Code.Password;
            // 验证注册码是否符合规则
            if (Calculated(Global.WindowLoginVM.Code) != 0)
            {
                MessageBox.Show("注册码错误！");
                IsUserLoggedIn = false;
                return -1;
            }
            else
            {
                string registrationCode = Global.encryption.Encrypt
                    (GetMachineCode() + Global.WindowLoginVM.Code + "/" + GetExpirationDate(Global.WindowLoginVM.Code));
                if (config.AppSettings.Settings.AllKeys.Contains("RegistrationCode"))
                {
                    if (GenerateRegistrationCode(config.AppSettings.Settings["RegistrationCode"].Value) != 0)
                    {
                        MessageBox.Show("注册码与本机不匹配！");
                        IsUserLoggedIn = false;
                        return -1;
                    }

                    if (!IsRegistrationCodeValid())
                    {
                        return -1;
                    }
                    //string decryptedCode = Global.encryption.Decrypt(config.AppSettings.Settings["RegistrationCode"].Value);
                    //string expirationDateStr = decryptedCode.Substring(decryptedCode.Length - 8);
                    //DateTime expirationDate = DateTime.ParseExact(expirationDateStr, "yyyyMMdd", null);
                    //string[] strings = decryptedCode.Split('/');
                    //if (DateTime.Now > expirationDate && strings[3].Equals(Global.WindowLoginVM.Code))
                    //{
                    //    MessageBox.Show("注册码已过期！");
                    //    IsUserLoggedIn = false;
                    //    return -1;
                    //}
                }

                settings.Settings.Remove("RegistrationCode");
                settings.Settings.Add("RegistrationCode", registrationCode);

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appsettings");
                return 0;
            }
        }
        public bool IsRegistrationCodeValid()
        {
            string decryptedCode = Global.encryption.Decrypt(config.AppSettings.Settings["RegistrationCode"].Value);
            string expirationDateStr = decryptedCode.Substring(decryptedCode.Length - 8);
            DateTime expirationDate = DateTime.ParseExact(expirationDateStr, "yyyyMMdd", null);
            string[] strings = decryptedCode.Split('/');

            if (DateTime.Now > expirationDate && strings[3].Equals(Global.WindowLoginVM.Code))
            {
                MessageBox.Show("注册码已过期！");
                IsUserLoggedIn = false;
                return false;
            }

            return true;
        }
        /// <summary>
        /// 注册码有效期
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private string GetExpirationDate(string code)
        {
            // 根据注册码长度确定有效期
            int days = 0;
            if (code.Length == 3)
                days = 3;
            else if (code.Length == 4)
                days = 7;
            else if (code.Length == 5)
                days = 15;
            else if (code.Length == 6)
                days = 30;
            else if (code.Length == 8)
                return new DateTime(2100, 1, 1).ToString("yyyyMMdd"); // 永久有效日期

            DateTime expirationDate = DateTime.Now.AddDays(days);
            return expirationDate.ToString("yyyyMMdd");
        }
        private static int Calculated(string input)
        {
            int digitSum = 0;
            foreach (char ch in input)
            {
                if (char.IsDigit(ch))
                    digitSum += int.Parse(ch.ToString());
                else if (char.IsLetter(ch))
                    digitSum += (char.ToUpper(ch) - 'A' + 1) > 10 ? (char.ToUpper(ch) - 'A' + 1) % 10 : char.ToUpper(ch) - 'A' + 1;
                else
                    digitSum += 1;
            }
            if (input.Length == 3)
                return digitSum == 10 ? 0 : -1;
            else if (input.Length == 4)
                return digitSum == 15 ? 0 : -1;
            else if (input.Length == 5)
                return digitSum == 20 ? 0 : -1;
            else if (input.Length == 6)
                return digitSum == 25 ? 0 : -1;
            else if (input.Length == 8)
                return input.Equals("20240425") ? 0 : -1;
            else
                return -1;
        }
        // 以后登录时验证注册码
        private int Login()
        {
            Global.WindowLoginVM.UserPassword = passwordBox.Password;
            if (Global.WindowLoginVM.UserName == "admin" && Global.WindowLoginVM.UserPassword == "0351")
                return 0;
            else
                return -1;
        }


        /// <summary>
        /// 机器码分割  
        /// </summary>
        /// <returns></returns>
        private static string GetMachineCode()
        {
            string machineCode = Environment.MachineName + "/" + Environment.UserName + "/" + Environment.OSVersion.VersionString + "/";
            return machineCode;
        }
        /// <summary>
        /// 机器码加密  
        /// </summary>
        /// <returns></returns>
        private static int GenerateRegistrationCode(string registrationCode)
        {
            string machineCode = GetMachineCode();
            if (Global.encryption.Decrypt(registrationCode).Contains(machineCode))
                return 0;
            else
                return -1;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter || e.Key == Key.Return)
            {
                Button_Click(loginButton, new RoutedEventArgs());
                // 在这里处理 Enter 键按下时的逻辑
                //MessageBox.Show("Enter 键已被按下");
            }
        }
    }
}

